package com.xu.system.auth.pwd;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xu.base.enums.ResponseCodeEnum;
import com.xu.base.utils.AssertUtils;
import com.xu.security.model.CurrentUser;
import com.xu.security.model.OnlineUser;
import com.xu.system.model.convert.UserConvert;
import com.xu.system.model.entity.SysUser;
import com.xu.system.service.db.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 密码用户服务
 *
 * @Author: 许乾伟
 * @Date: 2024/2/27 11:24
 */
@Service
public class PwdUserDetailsService implements UserDetailsService {
    @Resource
    UserConvert userConvert;

    @Resource
    ISysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq(SysUser.ACCOUNT,account);
        wrapper.eq(SysUser.IS_DELETE,Boolean.FALSE);
        SysUser sysUser = sysUserService.getOne(wrapper);
        AssertUtils.isNull(sysUser, ResponseCodeEnum.DATA_FAILED, "账号不正确，请重新输入");
        OnlineUser user = new OnlineUser();
//        user.setUserId(sysUser.getId());
        user.setPrincipal(sysUser.getAccount());
        user.setCredentials(sysUser.getPwd());
        CurrentUser currentUser = userConvert.toCurrentUser(sysUser);
//        currentUser.setHeadImageUrl(userService.getUserHeadImageUrl(sysUser.getId()));
        user.setUser(currentUser);
//        user.setRoles(roleService.getCurrentRoles(sysUser.getId()));
//        user.setMenus(menuService.getCurrentMenus(user.getRoles().stream().map(n -> n.getRoleId()).collect(Collectors.toList())));
        return user;
    }
}
